import React, { useMemo, useState, useEffect } from 'react'
import store from '../redux/store'
import getCinemaListAction from '../redux/action/getCinemaListAction'

export default function Search() {
    const [cinemaList, setList] = useState(store.getState().CinemaReducer.list)
    const [mytext, setText] = useState("")

    useEffect(() => {
        if (store.getState().CinemaReducer.list.length === 0) {
            store.dispatch(getCinemaListAction())
        } else {
            console.log("store cache");
        }
        var unsub = store.subscribe(() => {
            setList(store.getState().CinemaReducer.list)
        })
        return () => {
            // 取消订阅
            unsub()
        }
    }, [])

    const getCinemaList = useMemo(
        () =>
            cinemaList.filter(item => item.name.toUpperCase().includes(mytext.toUpperCase()) ||
                item.address.toUpperCase().includes(mytext.toUpperCase()))
        ,
        [cinemaList, mytext]
    )

    return (
        <div>
            <input value={mytext} onChange={(evt) => {
                setText(evt.target.value)
            }} />
            {
                getCinemaList.map(item =>
                    <dl key={item.cinemaId}>
                        <dt>{item.name}</dt>
                        <dd>{item.address}</dd>
                    </dl>
                )
            }

        </div>
    )
}
